<script>
import {createProps} from '@/utils';
import Constants from '@/components/hhd/design/FormEngine/Constants';
import FormEngineUtils from '@/components/hhd/design/FormEngine/FormEngineUtils';
import FieldDelegate from '@/components/hhd/design/FormEngine/FieldDelegate.vue';
import FieldRegistry from '@/components/hhd/design/FormField/FieldRegistry';

export default {
  name: 'FormComponentDelegate',
  props: {
    config: createProps(Object),
    context: createProps(Object),
  },
  render() {
    if (!this.config || !this.config || !this.context.formModel) return undefined;
    if (this.isField()) {
      return this.renderField();
    }
    if (this.isLayout()) {
      return this.renderLayout();
    }
    if (this.isSubForm()) {
      return this.renderSubForm();
    }
  },
  methods: {
    isSubForm() {
      return this.config && this.config.type === Constants.layout && this.config.subFormId;
    },
    renderSubForm() {
      return this.$createElement(FieldRegistry.subForm, {
        props: {
          config: this.config,
          context: this.context,
          dataSource: this.context.formModel[this.config.subFormId],
        },
        on: {
          updateSubFormData: () => this.context.updateSubFormData(),
        }
      });
    },
    renderLayout() {
      return this.$createElement(FieldRegistry.layout, {
        props: {
          config: this.config,
          context: this.context,
        }
      });
    },
    isLayout() {
      return this.config && this.config.type === Constants.layout && !this.config.subFormId;
    },
    isField() {
      return this.config && this.config.type === Constants.field;
    },
    renderField() {
      let fieldId = this.config.fieldId;
      let fieldConfig = FormEngineUtils.getFieldConfigById(fieldId, this.context.formDefinition);
      return this.$createElement(FieldDelegate, {
        props: {fieldConfig, context: this.context, formModel: this.context.formModel}
      });
    },
  }
};
</script>